package com.kqkj.dyrule.engine.queryService;

import com.kqkj.dyrule.engine.beans.EventParam;
import com.kqkj.dyrule.engine.beans.EventSequenceParam;

import java.sql.*;

public class ClickHouseQueryServiceImpl implements QueryService{
    Connection ckConn;
    public ClickHouseQueryServiceImpl(Connection ckConn){
        this.ckConn = ckConn;
    }
    public  long queryEventCountCondition(String deviceId,EventParam eventParam) throws SQLException{

        return queryEventCountCondition(deviceId,eventParam, eventParam.getTimeRangeStart(), eventParam.getTimeRangeEnd());

    }

    public long queryEventCountCondition(String deviceId, EventParam eventParam, long startTs, long endTs) throws SQLException {
        PreparedStatement pst = ckConn.prepareStatement(eventParam.getQuerySql());
        pst.setString(1,deviceId);
        pst.setLong(2,startTs);
        pst.setLong(3,endTs);
        ResultSet resultSet = pst.executeQuery();
        long result = 0;
        while(resultSet.next()){
            result = resultSet.getLong(1);
        }
        return result;

    }

    public int queryEventSequenceCondition(String deviceId, EventSequenceParam eventSequenceParam) throws SQLException {

        return queryEventSequenceCondition(deviceId,eventSequenceParam,eventSequenceParam.getTimeRangeStart(),eventSequenceParam.getTimeRangeEnd());
    }

    public int queryEventSequenceCondition(String deviceId, EventSequenceParam eventSequenceParam,long startTs,long endTs) throws SQLException {
        PreparedStatement pst = ckConn.prepareStatement(eventSequenceParam.getSequenceQuerySql());
        pst.setString(1,deviceId);
        pst.setLong(2,startTs);
        pst.setLong(3,endTs);
        ResultSet resultSet = pst.executeQuery();
        int maxStep =0;
        resultSet.next();
        //完成了几步
        for (int i =1;i<=eventSequenceParam.getEventSequence().size();i++){
            int v = resultSet.getInt(i);
            if (v == 1){
                //1代表成功，则计算成功了几步
                maxStep = eventSequenceParam.getEventSequence().size() - (i-1);
                break;
            }
        }
        return  maxStep;
    }


}
